/**
 * 用于缓存js对象
 * @type {Map}
 */
var cache = {};
/**
 * 日期增加格式化功能
 * @param format
 * @returns {*}
 */
Date.prototype.format = function(format){
    var o = {
        "M+" : this.getMonth()+1, //month
        "d+" : this.getDate(), //day
        "h+" : this.getHours(), //hour
        "m+" : this.getMinutes(), //minute
        "s+" : this.getSeconds(), //second
        "q+" : Math.floor((this.getMonth()+3)/3), //quarter
        "S" : this.getMilliseconds() //millisecond
    }

    if(/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
    }

    for(var k in o) {
        if(new RegExp("("+ k +")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length));
        }
    }
    return format;
}
/**
 * 按照名称填写页面元素内容
 * @param data
 * @param elementClass
 */
function initPageDataByName(data,elementClass) {
    initPageDate(data,"."+elementClass);

}
/**
 * 按照名称填写页面元素内容
 * @param data
 * @param selector
 */
function  initPageDate(data,selector) {
    $(selector).each(function (index,e) {
        var elementName  = $(e).attr("name");
        var tagName = $(e).prop("tagName");
        var  dataValue = data[elementName];
        if(isNullOrUndefined(dataValue)){
            dataValue="";
        }
        if(typeof   dataValue =="boolean" ){
            dataValue = JSON.stringify(dataValue);
        }

        if(tagName =='INPUT'){
            if($(e).attr("type") == 'radio' || $(e).attr('type') == 'RADIO') {
                if($(e).val() == dataValue) {
                    $(e).prop("checked","true");
                }
            }else if($(e).attr("type") == 'checkbox' || $(e).attr('type') == 'CHECKBOX'){
                var vals = dataValue.split('|');
                for(var i=0; i < vals.length; i++) {
                    if($(e).val() == vals[i]) {
                        $(e).prop("checked","true");
                    }
                }
            }else if( $(e).attr("data-type") == 'time'){
                if(dataValue>0){
                    var date = new Date(dataValue);
                    $(e).val( date.format("yyyy-MM-dd hh:mm:ss") );
                }

            }else{
                $(e).val( dataValue);
            }

        }else if(tagName =='SELECT'){
            $(e).val(dataValue);
        }else if(tagName =='TEXTAREA'){
            $(e).val(dataValue);
        }else if(tagName =='TD'){
            $(e).html( dataValue);
        }else if(tagName =='SPAN'){
            if($(e).attr("data-type") == 'time') {
                var date = new Date(dataValue);
                dataValue = date.format("yyyy-MM-dd hh:mm:ss");
            }
            $(e).html( dataValue);

        }else if(tagName =='DIV'){
            if($(e).attr("data-type") == 'time') {
                var date = new Date(dataValue);
                dataValue = date.format("yyyy-MM-dd hh:mm:ss");
            }
            $(e).html( dataValue);
        }else{
            $(e).html( dataValue);
        }
    });
}
/**
 * 通过名字后去元素对象
 * @param elementClass
 * @returns {{}}
 */
function getPageDataByClass(elementClass){
    return getPageDataBySelector("."+elementClass)
}
function getPageDataBySelector(selector){
    var data = {};
    $(selector).each(function (index,e) {
        var elementName  = $(e).attr("name");
        var tagName = $(e).prop("tagName");
        if(tagName =='INPUT'){
            if($(e).attr("type") == 'radio' || $(e).attr('type') == 'RADIO') {
                if($(e).is(":checked"))
                data[elementName] = $(e).val();
            }else if($(e).attr("type") == 'checkbox' || $(e).attr('type') == 'CHECKBOX'){
                if($(e).is(":checked")) {
                    data[elementName] = data[elementName] == undefined? $(e).val() : (data[elementName]+'|' + $(e).val());
                }
            }else{
                data[elementName] = $(e).val( );
            }
        }else if(tagName =='SELECT'){
            data[elementName] =$(e).val( );
        }else if(tagName =='TEXTAREA'){
            data[elementName] =$(e).val( );
        }
    });
    return data;
}

function initPage(element,curPage,totalPage,clickFun) {
    //清除生成的内容
    $(element).html("");
    if(totalPage <=1){
        return;
    }
    var options = {
        currentPage: curPage,
        totalPages: totalPage,
        onPageClicked:clickFun,
        numberOfPages: 1,
        itemTexts: function (type, page, current) {

            switch (type) {

                case "first":

                    return "首页";

                case "prev":

                    return "上一页";

                case "next":

                    return "下一页";

                case "last":

                    return "末页";

                case "page":

                    return page;

            }

        }
    }

    $(element).bootstrapPaginator(options);
}

/**
 * 居中打开界面
 * @param url
 * @param name
 * @param width
 * @param height
 */
function windowOpenCenter(url,name,width,height,modalDialog){
    var iWidth=width; //弹出窗口的宽度;
    var iHeight=height; //弹出窗口的高度;
    var iTop = (window.screen.availHeight-30-iHeight)/2; //获得窗口的垂直位置;
    var iLeft = (window.screen.availWidth-10-iWidth)/2; //获得窗口的水平位置;
    //费用列表和文件上传不能按照模态窗口打开
    if(0==modalDialog){
        window.open(url,name,"height="+iHeight+", width="+iWidth+", top="+iTop+", left="+iLeft);
    }else{
        if(isExitsFunction( window.showModalDialog)){
            window.showModalDialog(url,name,"dialogWidth:"+iWidth+"px;dialogHeight:"+iHeight+"px;dialogLeft:"+iLeft+"px;dialogTop:"+iTop+"px;location:no;resizable=no;status=no;center:yes;help:yes;resizable");
        }else{
            window.open(url,name,"height="+iHeight+", width="+iWidth+", top="+iTop+", left="+iLeft);
        }
    }



}
/**
 * 判断函数是否存在
 * @param funcName
 * @returns {boolean}
 */
function isExitsFunction(funcName) {
    try {
        if (typeof(funcName) != "undefined" && null != funcName) {
            return true;
        }
    } catch(e) {

    }
    return false;
}

function null2empty(data){
    if(typeof(data) == "undefined" ||data ==null){
        return "";
    }else{
        return data;
    }
}


//检验是否是空字符串
function strIsNull(str){
    if(str == undefined || str == null || str.replace(/\s/g,'') == ''){
        return true;
    }else{
        return false;
    }
}
//检验是否是整数
function isNumber(num){
    return /^\d+$/.test(num);
}
//检验是否是两位小数
function isFloat(num){
    return /^\d+(.\d{1,2})?$/.test(num);
}

function isNullOrUndefined(data) {
    if(data=='0'){
        return false;
    }
    if(typeof(data) == "undefined" || data ==null || (data ==""&&typeof data !="boolean")){
        return true;
    }else {
        return false;
    }
}

//截取字符串，多余的部分用...代替
function setString(str, len) {
    var strlen = 0;

    if(str != "" && typeof (str) !="undefined"){
        var s = "";
        for (var i = 0; i < str.length; i++) {
            strlen++;
            if (strlen >= len) {
                return s+"...";
            }
            s += str.charAt(i);

        }
        return s;
    }else{
        return str;
    }



}
/**
 * 获取当前时间的 格式化字符串
 * @returns {string}
 */
function getNowFormatDate(){
    var day = new Date();
    var Year = 0;
    var Month = 0;
    var Day = 0;
    var CurrentDate = "";
    Year= day.getFullYear();//支持IE和火狐浏览器.
    Month= day.getMonth()+1;
    Day = day.getDate();
    CurrentDate += Year+"-";
    if (Month >= 10 ){
        CurrentDate += Month+"-";
    }
    else{
        CurrentDate += "0" + Month+"-";
    }
    if (Day >= 10 ){
        CurrentDate += Day ;
    }
    else{
        CurrentDate += "0" + Day ;
    }
    return CurrentDate;
}
function getFirstDateForYear(year){
    var day = new Date();
    var Month = 0;
    var Day = 0;
    var CurrentDate = "";
    Month= 1;
    Day = 1;
    CurrentDate += year+"-";
    if (Month >= 10 ){
        CurrentDate += Month+"-";
    }
    else{
        CurrentDate += "0" + Month+"-";
    }
    if (Day >= 10 ){
        CurrentDate += Day ;
    }
    else{
        CurrentDate += "0" + Day ;
    }
    return CurrentDate;
}
function getDateZh(dataStr) {
    var yearIndex = dataStr.indexOf("年");
    var monthIndex = dataStr.indexOf("月");
    var dateIndex = dataStr.indexOf("日");
    var year = dataStr.substring(0,yearIndex);
    var  month = dataStr.substring(yearIndex+1,monthIndex);
    var date = dataStr.substring(monthIndex+1,dateIndex);
    var  d = new Date(year,month,date);
    return d;
}


function getFirstDateThisYear(){
    var day = new Date();
    var Year = 0;
    var Month = 0;
    var Day = 0;
    var CurrentDate = "";
    Year= day.getFullYear();//支持IE和火狐浏览器.
    Month= 1;
    Day = 1;
    CurrentDate += Year+"-";
    if (Month >= 10 ){
        CurrentDate += Month+"-";
    }
    else{
        CurrentDate += "0" + Month+"-";
    }
    if (Day >= 10 ){
        CurrentDate += Day ;
    }
    else{
        CurrentDate += "0" + Day ;
    }
    return CurrentDate;
}
/**
 * 初始化dataTable
 * @param element
 * @param ajaxUrl
 * @param param
 * @param columns
 * @param createdCellFun
 */
function initDataTable(element,ajaxUrl,param,columns,createdCellFun) {
    var dataTable = cache[element];
    if(!isNullOrUndefined(dataTable)){
        dataTable.destroy();
    }

    //清理元素
    $(element).children("tbody").remove();
    //禁用datatable 报错
    $.fn.dataTable.ext.errMode = 'none';
    //生成要展示的列
    var _columns = new Array();
    $(columns).each(function (index,data) {
        _columns.push( { "data": data });
    });

    dataTable = $(element).DataTable( {
        "processing": false,
        "serverSide": true,
        "searching": false,
        "ordering": false,
        "lengthChange": false,
        "retrieve": true,
        "paging":false,
        "info": false,
        "ajax": {
            "url": ajaxUrl,
            "type": "POST",
            "data": function (d) {
                for(var key in param){
                    d[key]=param[key];
                }
            }
        },
        "oLanguage" : {
            "sLengthMenu": "每页显示 _MENU_ 条记录",
            "sZeroRecords": "抱歉， 没有找到数据",
            "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
            "sInfoEmpty": "没有数据",
            "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
            "sZeroRecords": "没有检索到数据",
            "sSearch": "名称:",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "前一页",
                "sNext": "后一页",
                "sLast": "尾页"
            }
        },
        "columns": _columns,
        "columnDefs": [ {
            "targets": '_all',
            "createdCell": createdCellFun
        } ]
    } );
    cache[element]=dataTable;
}

//根据字典设置select元素
function initDictSelect(select,dicts,initValue){
    $(dicts).each(function(index,dict){
        $(select).append("<option value='"+dict.code+"'>"+dict.name+"</option>");
    });
    //初始化值
    if(typeof(initValue) != "undefined" && null != initValue && ""!=initValue) {
        $(select).val(initValue);
    }else if( ""==initValue) {
        $(select).append("<option value=''>全部</option>");
        $(select).val(initValue);
    }else {

    }

}
//初始化字典的select
function queryAndInitDictSelect(select,dictType,initValue){

    var param = {"type":dictType};

    $.ajax({
        type: "POST",
        url:"/admin/dict/list.json?_t=" + new Date().getTime(),
        data: param ,
        dataType:"json",
        async: false,
        success: function (result) {
            initDictSelect(select,result.data,initValue);
        },

        error: function (XMLHttpRequest, textStatus, thrownError) {
            /* alert("系统异常");*/
        }
    });

}
/**
 * 获取选中的多选框的值
 * @param name
 * @returns {Array}
 */
function getCheckBoxVule(name) {
    var chk_value =new Array();
    $("input[name="+name+"]:checked").each(function (index,element) {
        chk_value.push($(this).val());
    });
    return chk_value;
}
//获取要展示的图片
function getFileShowUrl(url){
    var extStart=url.lastIndexOf(".");
    var ext=url.substring(extStart,url.length).toUpperCase();
    if(ext!=".BMP"&&ext!=".PNG"&&ext!=".GIF"&&ext!=".JPG"&&ext!=".JPEG"){
        return "/resources/images/timg.jpg";
    }else{
        return url;
    }
}
//回退
function back(){
    window.history.go(-1);
}
function goto(url,data) {

    if(url.indexOf("?") >= 0){
        url = url+"&random="+new Date().getTime();
    }else {
        url = url+"?random="+new Date().getTime();
    }
    $(".right_col").load(url);
    setData(data);
}

function gotoLoginUrl(pathname){
    var  current = window.location.pathname;
    if(current !== pathname){
        window.location.pathname = pathname;
    }
}

function buildSelect(url,element,key,show,data,t) {
    $.ajax({
        type: "POST",
        url: url+"?_t=" + new Date().getTime(),
        data:data,
        dataType:"json",
        async: false,
        success: function (result) {
            $(result.data).each(function(index,item){
                $(element).append("<option value='"+item[key]+"' b-data='"+JSON.stringify(item)+"' >"+item[show]+"</option>");
            });
        },

        error: function (XMLHttpRequest, textStatus, thrownError) {
            /* alert("系统异常");*/
        }
    });
}
function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg); //匹配目标参数
    if (r != null) return unescape(r[2]); return null; //返回参数值
}
function tkClick(url) {
    QtFunction.qtOpenDefaultBrowser(url);
}